package com.tyqx.biz.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruiyun.jvppeteer.core.Puppeteer;
import com.ruiyun.jvppeteer.core.browser.Browser;
import com.ruiyun.jvppeteer.core.browser.BrowserFetcher;
import com.ruiyun.jvppeteer.core.page.Page;
import com.ruiyun.jvppeteer.options.BrowserOptions;
import com.ruiyun.jvppeteer.options.LaunchOptions;
import com.ruiyun.jvppeteer.options.LaunchOptionsBuilder;
import com.tyqx.apiutil.common.GetUrlUtil;
import com.tyqx.bean.model.EthPoolInfo;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class JsoupUtil {

    private static final Logger logger = LoggerFactory.getLogger(JsoupUtil.class);

    @Autowired
    private Constants constants;

    public List<EthPoolInfo> getEthPoolInfoList(String viewBlockUrl, String homeUrl) {
        logger.debug("进入方法getEthPoolInfoList");
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();

        List<EthPoolInfo> ethPoolInfoList = new ArrayList<>();
        try {

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");




            //2.创建get请求，相当于在浏览器地址栏输入 网址
            HttpGet request = new HttpGet(viewBlockUrl);

            //设置请求头，将爬虫伪装成浏览器
            request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
            //        HttpHost proxy = new HttpHost("60.13.42.232", 9999);
//        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
//        request.setConfig(config);

            //3.执行get请求，相当于在输入地址栏后敲回车键
//            response = httpClient.execute(request);


            //4.判断响应状态为200，进行处理
//            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            if (true) {
                //5.获取响应内容
//                HttpEntity httpEntity = response.getEntity();

//                String html = EntityUtils.toString(httpEntity, "utf-8");



                int sleepInterval = (int) (Math.random() * 10001);
                Thread.sleep(sleepInterval);
                //自动下载，第一次下载后不会再下载
                BrowserFetcher.downloadIfNotExist(null);
                ArrayList<String> argList = new ArrayList<>();
                ArrayList<String> argList1 = new ArrayList<>();

                LaunchOptions options = new LaunchOptionsBuilder().withArgs(argList).withIgnoreDefaultArgs(argList1).withHeadless(false).build();
                argList.add("--no-sandbox");
                argList.add("--disable-setuid-sandbox");
                argList1.add("--enable-automation");

//                Browser browser = Puppeteer.launch(options);

                String webSocketDebuggerUrl= constants.webSocketDebuggerUrl;

                Browser browser = Puppeteer.connect(new BrowserOptions(), webSocketDebuggerUrl, null, null, null);

                Page page = browser.newPage();
                page.goTo(viewBlockUrl);

                String content = page.content();
//                System.out.println("==========content===========");
//                System.out.println(content);

                String html = content;

//                browser.close();
                page.close();

                /**
                 * 下面是Jsoup展现自我的平台
                 */
                //6.Jsoup解析html
                Document document = Jsoup.parse(html);


                String url = "https://etherchain.org/api/basic_stats";
                String param = "";
                String basicStats = GetUrlUtil.GetUrl(url, param);
                JSONObject basicStatsJson = JSON.parseObject(basicStats);
                JSONObject currentStats = basicStatsJson.getJSONObject("currentStats");

                //当前eth全网算力
                BigDecimal currentHashrate = currentStats.getBigDecimal("hashrate");


                //当前区块难度
                BigDecimal currentDifficulty = currentStats.getBigDecimal("difficulty");

                currentHashrate = currentHashrate.movePointLeft(9).setScale(2, BigDecimal.ROUND_HALF_UP);

                currentDifficulty = currentDifficulty.movePointLeft(12).setScale(2, BigDecimal.ROUND_HALF_UP);
                Double difficulty = currentDifficulty.doubleValue();

                Double hashrate = currentHashrate.doubleValue();

                //像js一样，通过标签获取title
                //logger.debug(document.getElementsByTag("title").first());
                //像js一样，通过id 获取文章列表元素对象
                //Element postList = document.getElementById("post_list");
                Elements cardBody = document.getElementsByClass("card-body");
                //像js一样，通过class
                Elements tableResponsiveDiv = cardBody.get(0).getElementsByClass("table-responsive mb-2 mb-md-0");

                Element table = tableResponsiveDiv.get(0).getElementsByTag("table").get(0);

                Element tbody = table.getElementsByTag("tbody").first();


                Elements trElements = tbody.children();

                if (trElements.size() > 0) {
                    for (Element tr : trElements) {
                        //像jquery选择器一样，获取文章标题元素
                        Elements tdElements = tr.children();

                        EthPoolInfo ethPoolInfo = new EthPoolInfo();

                        ethPoolInfo.setCreateDate(dateFormat.parse(dateFormat.format(new Date())));

                        ethPoolInfo.setHashRate(hashrate);

                        ethPoolInfo.setDifficulty(difficulty);

                        if(tdElements.size()>=9){
                            for (int i = 0; i < tdElements.size(); i++) {
                                Element tdElement = tdElements.get(i);
                                switch (i) {
                                    case 0:
                                        Long block = Long.parseLong(tdElement.getElementsByTag("a").text().trim());
                                        ethPoolInfo.setBlock(block);
                                        break;
                                    case 1:
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        Date productDate = sdf.parse(tdElement.getElementsByTag("span").text().trim());
                                        ethPoolInfo.setProductDate(productDate);
                                        break;
                                    case 3:
                                        Long txn = new Long(0);
                                        if ("".equals(tdElement.getElementsByTag("a").text().trim())) {

                                        } else {
                                            txn = Long.parseLong(tdElement.getElementsByTag("a").text().trim());
                                        }
                                        ethPoolInfo.setTxn(txn);
                                        break;
                                    case 4:
                                        Long uncles = Long.parseLong(tdElement.text().trim());
                                        ethPoolInfo.setUncles(uncles);
                                        break;
                                    case 5:
                                        String miner = tdElement.getElementsByTag("a").text().trim();
                                        ethPoolInfo.setMiner(miner);
                                        break;
                                    case 6:
                                        String gasUsedText = tdElement.text().substring(0, tdElement.text().lastIndexOf("(")).trim();
                                        String[] gasUsedArr = gasUsedText.split(",");
                                        String gasUsedStr = "";
                                        for (String gasUsdeIndex :
                                                gasUsedArr) {
                                            gasUsedStr = gasUsedStr + gasUsdeIndex;
                                        }
                                        Long gasUsed = Long.parseLong(gasUsedStr.trim());
                                        String gasUsedScale = tdElement.getElementsByTag("span").text().trim();
                                        ethPoolInfo.setGasUsed(gasUsed);
                                        ethPoolInfo.setGasUsedScale(gasUsedScale);
                                        break;
                                    case 7:
                                        String gasLimitText = tdElement.text().trim();
                                        String[] gasLimitArr = gasLimitText.split(",");
                                        String gasLimitStr = "";
                                        for (String gasLimitIndex :
                                                gasLimitArr) {
                                            gasLimitStr = gasLimitStr + gasLimitIndex;
                                        }
                                        Long gasLimit = Long.parseLong(gasLimitStr);
                                        ethPoolInfo.setGasLimit(gasLimit);
                                        break;
                                    case 8:
                                        Double gasPrice = new Double(0.00);
                                        if (tdElement.text().contains("-")) {

                                        } else {
                                            if (tdElement.text().contains(",")) {
                                                String gasPriceText = tdElement.text().substring(0, tdElement.text().length() - 4).trim();
                                                String[] gasPriceArr = gasPriceText.split(",");
                                                String gasPriceStr = "";
                                                for (String gasPriceIndex :
                                                        gasPriceArr) {
                                                    gasPriceStr = gasPriceStr + gasPriceIndex;
                                                }
                                                gasPrice = Double.parseDouble(gasPriceStr);
                                            } else {
                                                gasPrice = Double.parseDouble(tdElement.text().substring(0, tdElement.text().length() - 4).trim());
                                            }
                                        }
                                        ethPoolInfo.setGasPrice(gasPrice);
                                        break;
                                    case 9:
                                        String rewardStr = tdElement.text().trim();
                                        rewardStr = rewardStr.substring(0, rewardStr.length() - 5);
                                        rewardStr = rewardStr.trim();
                                        Double reward = Double.parseDouble(rewardStr);
                                        ethPoolInfo.setReward(reward);
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }else{
                            logger.debug("td size < 9------");
                        }

                        ethPoolInfoList.add(ethPoolInfo);
                    }
                }else{
                    logger.debug("tr size 0-------------");
                }



            } else {
                //如果返回状态不是200，比如404（页面不存在）等，根据情况做处理，这里略
                logger.debug("返回状态不是200");
                logger.debug(EntityUtils.toString(response.getEntity(), "utf-8"));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //6.关闭
            HttpClientUtils.closeQuietly(response);
            HttpClientUtils.closeQuietly(httpClient);
        }
        return ethPoolInfoList;
    }
}
